<?php
/*
Primary Author: Derek Shue
Secondary: Alex Arey (primary for internshipapplicationAction), Sean Margison
Updated: 12/11/2011
Module Description: The student controller is responsible for student actions including
browsing internships, internships, and courses and for submitting and viewing internship
applications
*/
class StudentController extends Zend_Controller_Action
{
	/**
	* Init checks user session exists and redirects otherwise.
	*/
    public function init()
    {
        $auth = Zend_Auth::getInstance(); 
		if($auth->hasIdentity()){
			$studentID = $auth->getIdentity()->getUID();
		}else{
			$this->_helper->redirector('index','index');
			return;
		}
    }
    
    public function indexAction(){
		return $this->_helper->redirector('browseinternships');
    }
	/**
	* browseinternships provides a summary view of internships and searches available internships.
	* without search criteria (ie on first load) the page displays current and future terms' internships.
	*/
    public function browseinternshipsAction(){
		$auth = Zend_Auth::getInstance(); 
		$studentID = $auth->getIdentity()->getUID();
		$positionQuery = new Application_Model_InternshipQuery();
		
		$form = new Application_Form_Search();
		$this->view->form = $form;
		$date = new Zend_Date();
		
		if ($this->getRequest()->isPost()) {
		        $formData = $this->getRequest()->getPost();
				$positions = null;
		        if ($form->isValid($formData)) {		
					if($form->getValue('YEAR') == ""){
		        		$term = array('term'=>$form->getValue('TERM') , 'year' => $date->get(Zend_Date::YEAR));
		        	}else{
		        		$term = array('term'=>$form->getValue('TERM') , 'year' => $form->getValue('YEAR'));
		        	}
		            $termmodifier = $form->getValue('MODIFIER');
					$name = $form->getValue('NAME');
					$positions = $positionQuery->selectInternships_Student($term, $termmodifier, $name);
			    }
			}
		else{
				$positions = $positionQuery->getInternships_Student();
			}
		$orgs = array();
		$dbtOrgs = new Application_Model_DbTable_Organizations();
		foreach($positions as $pos){
			$p=$dbtOrgs->getOrganization('ID = '.$pos['CPID']);
			$orgs[$pos['CPID']] = $p['NAME'];
		}
		$this->view->organizationnames = $orgs;
		$this->view->positions = $positions;
    }
    
    /**
    * Provides a view of all the student's past internship applications.
    * No search provided because there will usually not be enough data to require it.
    */
    public function myapplicationsAction(){
        $auth = Zend_Auth::getInstance(); 
		if($auth->hasIdentity()){
			$studentID = $auth->getIdentity()->getUID();
		}else{
			$this->_helper->redirector('index','index');
			return;
		}
		$applicationQuery = new Application_Model_DbTable_Applications();
		$results = $applicationQuery->getApplications('SID = '.$studentID);
		$apps = array();
		foreach($results as $res){
			$internapp = new Application_Model_InternshipApp();
			$internapp->init($res['APPID']);
			$apps[] = $internapp;
		}
		$this->view->applications = $apps;
    }


	/**
	* Provides a view of all courses and processes a search form for all courses.
	* If no query is given (ie on first load) defaults to present and future.
	*/
    public function browsecoursesAction(){

		$auth = Zend_Auth::getInstance(); 
		if($auth->hasIdentity()){
			$studentID = $auth->getIdentity()->getUID();
		}else{
			$this->_helper->redirector('index','index');
			return;
		}
		
		$form = new Application_Form_CourseSearch();
		$this->view->form = $form;

		$courseQuery = new Application_Model_CoursesQuery();
		//set defaults
		$termModifier = 'ns';
		$term = '';
		$coursename = '';
		$coursenumber = 0;
		$date = new Zend_Date();
				
		//overwrite defaults with form data
		if ($this->getRequest()->isPost()) {
		        $formData = $this->getRequest()->getPost();
		        if ($form->isValid($formData)) {		
					if($form->getValue('YEAR') == ""){
		        		$term = array('term'=>$form->getValue('TERM') , 'year' => $date->get(Zend_Date::YEAR));
		        	}else{
		        		$term = array('term'=>$form->getValue('TERM') , 'year' => $form->getValue('YEAR'));
		        	}
		            $termmodifier = $form->getValue('MODIFIER');
					$coursename = $form->getValue('COURSENAME');
					$coursenumber = $form->getValue('COURSENUMBER');
					$courses = $courseQuery->selectCourses_Student($term, $termmodifier, $coursename, $coursenumber);
			    }
			}
		else{
				$courses = $courseQuery->getCourses_Student();
			}
		$this->view->entries = $courses;
    }


	/**
	* Handles the internship application process. 
	* Applicant can arrive at this action controller to display either the primary form or the reference form, or to 
	* process either form or to delete a reference.
	* All these are handled in the order - check external prerequisites, check reference form display,
	* check reference form submit, reference delete, form submit 
	*/
    public function internshipapplicationAction(){
		$auth = Zend_Auth::getInstance(); //verify applicant is logged in.
		if($auth->hasIdentity()){
			$studentID = $auth->getIdentity()->getUID();
		}else{
			$this->_helper->redirector('index','index');
			return;
		}
		//check if there is a valid term for the student to apply for. will prevent from continuing if so.
		try{
			$termQuery = new Application_Model_Term();
			$success = $termQuery->getCurrentOpenTerm('stuapp')!=null;
			if(!$success){
				throw new Exception("There are currently no sessions open for submission.");//thrown exception caught below
			}	
		}
		catch(Exception $e){
			$this->view->open = false;//this indicates to the view what error should be shown.
			return null;
		}
		$this->view->open = true;
		
		//check if student has a submitted application for the semester. will prevent from continuing if so.
		$term = new Application_Model_Term();
		$apps = new Application_Model_DbTable_Applications();
		$currapps = $apps->getApplications('SID = '.$studentID.' and TERM = \''.$term->getCurrentOpenTermStr('stuapp').'\'');
		if(count($currapps)>0){
			$this->view->existingapplication = true;//indicates to the view what text should be shown.
			return;
			}
		try{
			$dbtStu = new Application_Model_DbTable_Students();
			$query = 'ID = '.$studentID;
			$studentInfo = $dbtStu->getStudent($query);
			$this->view->studentInfo = $studentInfo;
		}catch(Exception $e){
			$this->view->studentInfo = null;
		}
		//keep intern application in namespace to preserve persistence while adding references.
		//this namespace is cleared on submit.
		$ns = new Zend_Session_Namespace('Default');
		if (!isset($ns->internapp)) {
    		$ns->internapp = new Application_Model_InternshipApp();
		} 
		$ns->internapp->getStudentData($studentID);
		$app = $ns->internapp;
		$this->view->references = $app->_references;//get references from session
		//references in session are used to provide the multi-page form that navigates between references
		//and the main application page.
		
		$form = new Application_Form_InternshipApplication();
		$refform = new Application_Form_InternshipReference();
		$this->view->form = $form;
		//process reference form indicated by 'reference' get parameter == 'add'
		if($this->getRequest()->getParam('reference')=="add"){
			$this->view->refform = $refform;
			if ($this->getRequest()->isPost()) {
				$formData = $this->getRequest()->getPost();
				if ($refform->isValid($formData)) {
					$app->addReference(
						$refform->getValue('referencerelation'),
						$refform->getValue('referencename'),
						$refform->getValue('referencephone'),
						$refform->getValue('referenceaddr1'),
						$refform->getValue('referenceaddr2'),
						$refform->getValue('referencecity'),
						$refform->getValue('referencestate'),
						$refform->getValue('referencezip')
					);
					$this->_helper->redirector('internshipapplication', 'student');//redirect back application
				}
			}
		}
		//process remove reference indicated by get parameter, and redirect back to application.
		if($this->getRequest()->getParam('reference')=="remove"){
		
			$app->removeReference(
				$this->getRequest()->getParam('name'),
				$this->getRequest()->getParam('phone')
			);
			$this->_helper->redirector('internshipapplication', 'student');
		}
		//finally, if no other flags were set, we submitted the real application and must process it.
		else if ($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();
			if (count($app->_references)>=3){
				if ($form->isValid($formData)) {
					$app->_year = $form->getValue('year');
					$app->_gpa = $form->getValue('gpa');
					$app->_transport = $form->getValue('transport');
					$app->_experience = $form->getValue('experience');
					$app->_issueText = $form->getValue('issue');
					$app->_courseWork = $form->getValue('coursework');
					
					$check_resume = $form->getValue('resume');
					//ensure resume url has http://, this is needed to ensure it links correctly in views
					if(substr($check_resume,0,7)=="http://"){
						$app->_resumeURL = $form->getValue('resume');
					}else{
						$app->_resumeURL = $check_resume;
					}
					//check if any two position preferences values are the same, set error othw
					if($form->getValue('pref1')!=$form->getValue('pref2')&&
					   $form->getValue('pref1')!=$form->getValue('pref3')&&
					   $form->getValue('pref2')!=$form->getValue('pref3'))
					{
						$app->addWillingPosition($form->getValue('pref1'),1,$form->getValue('pref1text'));
						$app->addWillingPosition($form->getValue('pref2'),2,$form->getValue('pref2text'));
						$app->addWillingPosition($form->getValue('pref3'),3,$form->getValue('pref3text'));
						$app->saveToDB();
						unset($ns->internapp);//remove application data from session.
						$this->_helper->redirector('index','index');
					}else{
						$this->view->willingposerror = true;//set error if willing positions were duplicated
					}	
				}
			}
			else{
				$this->view->numcontactserror = true;//set error if not enough contacts submitted
				//shouldn't be an issue due to view organization
			}
		}
    }
	
	/**
	* Displays details for an internship position the applicant has been suggested for.
	*/
	public function viewinternshipAction(){
    	$auth = Zend_Auth::getInstance(); 
		if($auth->hasIdentity()){
			$studentID = $auth->getIdentity()->getUID();
		}else{
			$this->_helper->redirector('index','index');
			return;
		}
		//get position data
		$positionQuery = new Application_Model_InternshipQuery();
		try{
			$row = $positionQuery->selectInternship_ID($this->getRequest()->getParam('position'));
			if($row['POSITIONSGRANTED'] == 0){
				$this->view->position = null;
			}else{
				$this->view->position = $row;
			}
		}catch(Exception $e){
			$this->view->position = null;
		}
    }
	
	
}
